<script setup>

import {ElButton, ElCard, ElInput, ElMessage, ElMessageBox} from "element-plus";
import {Delete, Edit, Refresh} from "@element-plus/icons-vue";
import {onMounted, ref} from "vue";
import {userInfoStore} from "@/store/userInfoStore.js";
import {GetUserList,DeleteUser} from "@/api/user.js";
import { Picture as IconPicture } from '@element-plus/icons-vue'
import AddUserComponent from "@/components/admin/userAdmin/AddUserComponent.vue";
import UpdateUserComponent from "@/components/admin/userAdmin/UpdateUserComponent.vue";
import {DeleteApp} from "@/api/app.js";
import AddAppComponent from "@/components/admin/appAdmin/AddAppComponent.vue";
import AddScoringComponent from "@/components/admin/ScoringStrategyAdmin/AddScoringComponent.vue";
import UpdateAppComponent from "@/components/admin/appAdmin/AdminUpdateAppComponent.vue";
import {ListScoringByPage} from "@/api/scoring.js";

const current = ref(1) //当前页
const pageSize = ref(10) //每页条数
const total = ref(20) //总条数
//分页条数据模型
const form = ref({
  // 分页参数
  pageSize: 10, // 每页显示数量
  current: 1,   // 当前页码

  // 排序参数
  sortField: '', // 排序字段
  sortOrder: '',   // 排序顺序（asc/desc）

  // 评分标准参数
  isDelete: null,     // 是否删除（0-未删除，1-已删除）
  appId: null,     // 所属应用ID
  userId: null,    // 所属用户ID

  // 评分标准详情
  id: null,        // 评分标准ID（编辑时使用）
  resultName: '',  // 结果名称（最大80字符）
  resultDesc: '',  // 结果描述（最大80字符）
  resultProp: '',  // 结果属性（最少1个内容）
  resultScoreRange: null, // 得分范围

  // 其他查询参数
  notId: null      // 不需要的ID（排除特定记录）
})
const fields = ref(
  {
          "评判标准ID":"id",
          "应用ID":"appId",
          "用户Id":"userId",
          "结果名称":"resultName",
          "得分范围":"resultScoreRange",
      }
)
const tableData = ref([])

const clearForm = () => {
  form.value={
    // 分页参数
    pageSize: 10, // 每页显示数量
    current: 1,   // 当前页码

    // 排序参数
    sortField: '', // 排序字段
    sortOrder: '',   // 排序顺序（asc/desc）

    // 评分标准参数
    isDelete: null,     // 是否删除（0-未删除，1-已删除）
    appId: null,     // 所属应用ID
    userId: null,    // 所属用户ID

    // 评分标准详情
    id: null,        // 评分标准ID（编辑时使用）
    resultName: '',  // 结果名称（最大80字符）
    resultDesc: '',  // 结果描述（最大80字符）
    resultProp: '',  // 结果属性（最少1个内容）
    resultScoreRange: null, // 得分范围

    // 其他查询参数
    notId: null      // 不需要的ID（排除特定记录）
  }
}

const fetchScoreList = async () => {
  // 将表单值赋给params对象
  const params = {
    id: (form.value.id !== null && form.value.id > 0) ? form.value.id : null,
    resultName: form.value.resultName === '' ? null : form.value.resultName,
    resultDesc: form.value.resultDesc === '' ? null : form.value.resultDesc,
    resultProp: form.value.resultProp === '' ? null : form.value.resultProp,
    resultScoreRange: form.value.resultScoreRange !== null ? form.value.resultScoreRange : null,
    appId: (form.value.appId && form.value.appId > 0) ? form.value.appId : null,
    userId: (form.value.userId && form.value.userId > 0) ? form.value.userId : null,
    notId: (form.value.notId && form.value.notId > 0) ? form.value.notId : null,
    sortField: form.value.sortField === '' ? null : form.value.sortField,
    sortOrder: form.value.sortOrder === '' ? null : form.value.sortOrder,
    current: current.value,
    pageSize: pageSize.value,
    isDelete: (form.value.isDelete !== null && form.value.isDelete >= 0) ? form.value.isDelete : null
  }
  //获取用户列表 todo 获取列表的函数改一下
  const answer = await ListScoringByPage(params);
  console.log("answer: ", answer)
  ElMessage.success("搜索成功！")
  tableData.value = answer.data.scoring_results ||[];
  total.value = answer.data.total;
  current.value = answer.data.current;
  pageSize.value = answer.data.pageSize;
  console.log("tableData: ",tableData.value)
}
// todo 改
onMounted(async ()=>{
  await fetchScoreList();
  console.log("Strategy_list",tableData.value)
})
//当每页条数发生了变化，调用此函数
const onSizeChange = async (size) => {
  pageSize.value = size;
  await fetchScoreList();
};
//当前页码发生变化，调用此函数
const onCurrentChange = async (num) => {
  current.value = num;
  await fetchScoreList()
};

//添加用户
const addScoringRef = ref(null);

const openAddScoringDialog = async () => {
  if (addScoringRef.value) {
    addScoringRef.value.showAddScoringDialog();
  }
};
//更新App
const updateScoringRef = ref(null);
const openUpdateScoringDialog = (row) => {
  if (updateScoringRef.value) {
    console.log("row.id：",row.id)
    updateScoringRef.value.showUpdateScoringDialog(row);
  }
}
//删除用户
const DeleteForScoring = async (row)=>{
  ElMessageBox.confirm(
      row.isDelete===0?'此操作将删除该结果种类，是否确认删除？':'此操作将恢复该结果种类，是否确认恢复？',
      '温馨提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        console.log(row.id)
        await DeleteScoring(row.id);
        await fetchScoreList();
        if(row.isDelete===0) {
          ElMessage.success("删除成功！")
        }else{
          ElMessage.success("恢复成功！")
        }
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '按钮取消!',
        })
      })
}
</script>

<template>
  <el-card class="page-container">
    <div>{{tableData.value}}</div>
    <template #header>
      <div class="header">
        <span>评分策略管理</span>
        <div class="extra">
          <!--# todo 改-->
          <el-button type="primary" @click="openAddScoringDialog">添加评分策略</el-button>
          <AddScoringComponent ref="addScoringRef" @call-parent="fetchScoreList" />
        </div>
      </div>
    </template>
    <!-- 搜索表单 -->
    <el-form inline class="user-list">
      <!--todo 这里要与后端的搜索用户的数据一致，添加一样多的搜索框 -->
<!--      <el-form-item label="用户ID：">-->
<!--        <el-input v-model="form.id" />-->
<!--      </el-form-item>-->
      <el-form-item label="评分结果名称：">
        <el-input v-model="form.resultName" />
      </el-form-item>
      <el-form-item label="评分结果描述：">
        <el-input v-model="form.resultDesc" />
      </el-form-item>
      <el-form-item label="应用id：">
        <el-input v-model="form.appId" />
      </el-form-item>
      <el-form-item label="用户id：">
        <el-input v-model="form.userId" />
      </el-form-item>
      <el-form-item label="是否删除：">
        <el-select v-model="form.isDelete" placeholder="请选择" style="width: 240px">
          <el-option label="所有" value=-1></el-option>
          <el-option label="正常" value=0></el-option>
          <el-option label="删除" value=1></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="排序字段：">
        <el-select placeholder="请选择" v-model="form.sortField" style="width: 240px">
          <el-option v-for="([label, value]) in Object.entries(fields)" :key="value" :label= "label" :value="value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="排序方式：">
        <el-select placeholder="请选择" v-model="form.sortOrder" style="width: 240px">
          <el-option label="升序" value="asc"></el-option>
          <el-option label="降序" value="desc"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item class="button-group">
        <!-- todo 改 -->
        <el-button type="primary" @click="fetchScoreList"
        >搜索</el-button
        >
        <el-button
            @click="
            clearForm();
            fetchScoreList();
            ElMessage.success('重置成功！')
          "
        >重置</el-button
        >
      </el-form-item>
    </el-form>
    <!-- 文章列表 -->
    <el-table :data="tableData" style="width: 100%">
      <el-table-column
          type="index"
          label="序号"
          width="50"
      ></el-table-column>
      <el-table-column
          label="测评ID"
          prop="id"
      ></el-table-column>
      <el-table-column
          label="名称"
          prop="resultName"
      ></el-table-column>
      <el-table-column
          label="描述"
          prop="resultDesc"
      ></el-table-column>
      <el-table-column label="图片" prop="resultPicture">
        <template #default="scope">
          <el-image
              style="width: 100px; height: 100px"
              :src="scope.row.resultPicture||'D:\\WebStorm 2024.1.5\\repository\\fronted\\src\\assets\\avatar.jpg'"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :preview-src-list="[scope.row.resultPicture||'D:\\WebStorm 2024.1.5\\repository\\fronted\\src\\assets\\avatar.jpg']"
              :preview-teleported="true"
              show-progress
              fit="cover"
          >
            <template #error>
              <div class="image-slot">
                <el-icon><icon-picture /></el-icon>
              </div>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="结果属性" prop="resultProp">
      </el-table-column>
      <el-table-column label="评分范围" prop="resultScoreRange"> </el-table-column>
      <el-table-column label="用户id" prop="userId">
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime"> </el-table-column>
      <el-table-column label="更新时间" prop="updateTime"> </el-table-column>
      <el-table-column label="状态" prop="isDelete">
        <template #default="{ row }">
          <el-text class="mx-1" type="success" v-if="row.isDelete === 0">正常</el-text>
          <el-text class="mx-1" type="danger" v-else>已删除</el-text>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button
              :icon = Edit
              circle
              plain
              type="primary"
              @click="openUpdateScoringDialog(row)" >  </el-button>
          <UpdateAppComponent ref="updateScoringRef" @call-parent="fetchScoreList"/>
          <el-button
              :icon="Delete"
              circle
              plain
              type="danger"
              @click="DeleteForScoring(row)"
              v-if="row.isDelete === 0"
          ></el-button>
          <el-button
              :icon="Refresh"
              circle
              plain
              type="success"
              @click="DeleteForScoring(row)"
              v-if="row.isDelete === 1"
          ></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
    <!-- 分页条 -->
    <el-pagination
        v-model:current-page="form.current"
        v-model:page-size="form.pageSize"
        :page-sizes="[3, 5, 10, 15]"
        layout="jumper, total, sizes, prev, pager, next"
        background
        :total="total"
        @size-change="onSizeChange"
        @current-change="onCurrentChange"
        style="margin-top: 20px; justify-content: flex-end"
    />
  </el-card>
</template>

<style scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .user-list {
    display: flex;
    flex-wrap: wrap;
    gap: 16px; /* 表单项之间的间距 */
    align-items: center;
  }

  .user-list el-form-item {
    margin-bottom: 0; /* 移除默认的底部间距 */
  }

  .button-group {
    margin-left: auto; /* 将按钮组推到右侧 */
  }

  el-image {
    position: relative;
    z-index: 1;
  }
  .el-image-viewer__img {
    z-index: 9999 !important;
  }
}
</style>


